package org.hepeng.fabric.gateway.pool.spring.interceptor;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.hepeng.fabric.gateway.pool.FabricGatewayHolder;
import org.hepeng.fabric.gateway.pool.FabricGatewayObject;
import org.hepeng.fabric.gateway.pool.GatewayKey;
import org.hepeng.fabric.gateway.pool.GatewayKeyProvider;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author he peng
 * @date 2022/3/24
 */
public class FabricGatewayInterceptor implements AsyncHandlerInterceptor {

    private final GenericKeyedObjectPool<GatewayKey, FabricGatewayObject> gatewayPool;

    private final GatewayKeyProvider keyProvider;

    public FabricGatewayInterceptor(GenericKeyedObjectPool<GatewayKey , FabricGatewayObject> gatewayPool, GatewayKeyProvider keyProvider) {
        this.gatewayPool = gatewayPool;
        this.keyProvider = keyProvider;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        FabricGatewayObject fabricGatewayObject = gatewayPool.borrowObject(keyProvider.getKey(request));
        FabricGatewayHolder.set(fabricGatewayObject);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        FabricGatewayObject fabricGatewayObject = FabricGatewayHolder.remove();
        gatewayPool.returnObject(fabricGatewayObject.getKey() , fabricGatewayObject);
    }
}
